package com.rednose.videoplayer.adapters;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.rednose.videoplayer.model.MediaFiles;
import com.rednose.videoplayer.R;
import com.rednose.videoplayer.utils.Utility;
import com.rednose.videoplayer.activities.VideoPlayerActivity;
import com.rednose.videoplayer.controller.LoginController;
import com.rednose.videoplayer.controller.PlayListController;
import com.rednose.videoplayer.model.User;

import java.util.ArrayList;

public class PlayListAdapter extends RecyclerView.Adapter<PlayListAdapter.ViewHolder> {
    private ArrayList<MediaFiles> videoList;
    private Context context;
    BottomSheetDialog bottomSheetDialog;
    private int viewType;

    public PlayListAdapter(ArrayList<MediaFiles> videoList, Context context, int viewType) {
        this.videoList = videoList;
        this.context = context;
        this.viewType = viewType;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.video_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.videoName.setText(videoList.get(position).getDisplayName());//设置视频名称

        double milliSeconds = Double.parseDouble(videoList.get(position).getDuration());//获取视频时长
        holder.videoDuration.setText(Utility.timeConversion((long) (milliSeconds)));//转化格式，设置视频时长

        holder.videoSize.setText(android.text.format.Formatter.formatFileSize(
                context, Long.parseLong(videoList.get(position).getSize())));//设置视频大小

        //设置视频缩略图
        Glide.with(context)
                .load(videoList.get(position).getPath())
                .into(holder.thumbNail);


        //设置菜单的点击事件
        holder.menuMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog = new BottomSheetDialog(context, R.style.BottomSheetTheme);       //创建底部弹窗
                View bsView = LayoutInflater.from(context).inflate(R.layout.list_bs_layout,
                        v.findViewById(R.id.bottom_sheet_list));                                         //加载底部弹窗布局
                //播放视频
                bsView.findViewById(R.id.bs_list_play).setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        holder.itemView.performClick();                                 //模拟点击事件,跳转播放视频的活动
                        bottomSheetDialog.dismiss();                                    //关闭底部弹窗
                    }
                });
                //从列表中删除
                bsView.findViewById(R.id.bs_list_delete).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(context);    //创建对话框
                        builder.setTitle("删除视频")                                        //设置标题
                                .setMessage("确定要从列表删除此视频吗？（注意：此操作不会从本地删除视频）")                          //设置内容
                                .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //执行数据库删除逻辑
                                        MediaFiles deleteFile = videoList.get(position);        //获取要删除的视频
                                        User user = (new LoginController(context)).getUser(Utility.getCurrentUser(context)); //获取当前用户
                                        PlayListController playListController = new PlayListController(context); //获取播放列表控制器
                                        playListController.deleteFromPlayList(deleteFile, user); //删除视频
                                        //执行列表删除逻辑
                                        videoList.remove(position);                                //移除视频
                                        notifyItemRemoved(position);                            //通知移除
                                        notifyItemRangeChanged(position, videoList.size());     //通知范围改变
                                        dialog.dismiss();                                        //关闭对话框
                                        bottomSheetDialog.dismiss();                            //关闭底部弹窗
                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();                                        //关闭对话框
                                    }
                                });
                        builder.create().show();                                            //显示对话框
                    }
                });
                //属性
                bsView.findViewById(R.id.bs_list_properties).setOnClickListener(new View.OnClickListener(){

                    @Override
                    public void onClick(View view) {
                        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);     //创建一个弹窗
                        alertDialog.setTitle("属性");                                     //设置标题

                        String one = "文件名: " + videoList.get(position).getDisplayName();           //设置属性，文件名

                        String path = videoList.get(position).getPath();                            //获取视频路径
                        int indexOfPath = path.lastIndexOf("/");
                        String two = "路径: " + path.substring(0, indexOfPath);                     //设置属性，路径
                        //设置属性，大小
                        String three = "大小: " + android.text.format.Formatter
                                .formatFileSize(context, Long.parseLong(videoList.get(position).getSize()));

                        String four = "时长: " + Utility.timeConversion((long) milliSeconds);                 //设置属性，时长

                        String namewithFormat = videoList.get(position).getDisplayName();           //获取视频名称
                        int index = namewithFormat.lastIndexOf(".");
                        String format = namewithFormat.substring(index + 1);
                        String five = "格式: " + format;                                          //设置属性，格式

                        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();    //创建一个媒体元数据检索器
                        metadataRetriever.setDataSource(videoList.get(position).getPath());         //设置数据源
                        String height = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);    //获取视频高度
                        String width = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);      //获取视频宽度
                        String six = "分辨率: " + width + "x" + height;                         //设置属性，分辨率

                        alertDialog.setMessage(one + "\n\n" + two + "\n\n" + three + "\n\n" + four +
                                "\n\n" + five + "\n\n" + six);                                                  //设置消息
                        alertDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {     //设置确定按钮
                            @Override
                            public void onClick(DialogInterface dialog, int which) {                        //点击确定按钮后
                                dialog.dismiss();                                                           //关闭弹窗
                            }
                        });
                        alertDialog.show();                                                             //显示弹窗
                        bottomSheetDialog.dismiss();                                                    //关闭底部弹窗
                    }
                });

                bottomSheetDialog.setContentView(bsView);                               //设置底部弹窗的布局
                bottomSheetDialog.show();                                               //显示底部弹窗

            }
        });

        //设置整个控件item的点击事件
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转播放视频的活动
                Intent intent = new Intent(context, VideoPlayerActivity.class);
                intent.putExtra("position",position);                                       //传递视频位置
                intent.putExtra("video_title", videoList.get(position).getDisplayName());   //传递视频名称
                Bundle bundle = new Bundle();
                bundle.putParcelableArrayList("videoArrayList",videoList);                        //传递视频列表
                intent.putExtras(bundle);                                                         //传递bundle
                context.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return videoList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        ImageView thumbNail, menuMore;
        TextView videoName, videoDuration, videoSize;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            thumbNail = itemView.findViewById(R.id.thumbnail);
            menuMore = itemView.findViewById(R.id.video_menu_more);
            videoName = itemView.findViewById(R.id.video_name);
            videoDuration = itemView.findViewById(R.id.video_duration);
            videoSize = itemView.findViewById(R.id.video_size);
        }
    }
}
